#ifndef _THREAD_POOL_H_
#define _THREAD_POOL_H_

#include <condition_variable>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>
#include <stdexcept>

class ThreadPool
{
public:
    ThreadPool(size_t);

    // 添加任务队列
    template <class F, class... Args>
    auto enqueue(F &&f, Args &&...args)
        -> std::future<typename std::result_of<F(Args...)>::type>;
    ~ThreadPool();

    bool IsTasksEmpty();
    int TasksSize();

private:
    // 存储线程对象
    std::vector<std::thread> workers;

    // 任务队列
    std::queue<std::function<void()>> tasks;
    // 互斥锁
    std::mutex queue_mutex;
    std::condition_variable condition;
    bool stop;
};

#endif

inline ThreadPool::ThreadPool(size_t threads) : stop(false)
{
    for (size_t i = 0; i < threads; ++i)
    {
        workers.emplace_back(
            [this]
            {
                for (;;)
                {
                    // 定义任务
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(this->queue_mutex);
                        this->condition.wait(lock,
                                             [this]
                                             { return this->stop || !this->tasks.empty(); });

                        if (this->stop && this->tasks.empty())
                            return;

                        task = std::move(this->tasks.front());
                        this->tasks.pop();
                    }
                    // 执行任务
                    task();
                }
            });
    }
}

// add new work item to the pool
template <class F, class... Args>
auto ThreadPool::enqueue(F &&f, Args &&...args)
    -> std::future<typename std::result_of<F(Args...)>::type>
{
    // 获取f执行后的类型
    using return_type = typename std::result_of<F(Args...)>::type;

    // 获得一个智能指针 指向一个被包装为return_type()的task
    auto task = std::make_shared<std::packaged_task<return_type()>>(
        std::bind(std::forward<F>(f), std::forward<Args>(args)...));

    // 获取执行结果
    std::future<return_type> res = task->get_future();

    // 添加任务到队列
    {
        std::unique_lock<std::mutex> lock(queue_mutex);

        // don't allow enqueueing after stopping the pool
        if (stop)
            throw std::runtime_error("enqueue on stopped ThreadPool");

        tasks.emplace([task]()
                      { (*task)(); });
    }

    // 通知一个线程
    condition.notify_one();
    return res;
}

inline ThreadPool::~ThreadPool()
{
    // 更改停止标识
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        stop = true;
    }
    // 通知所有阻塞中的线程
    condition.notify_all();

    // 确保线程执行完成
    for (std::thread &worker : workers)
        worker.join();
}

// 检查队列
inline bool ThreadPool::IsTasksEmpty()
{
    std::unique_lock<std::mutex> lock(queue_mutex);
    return tasks.empty();
}

// 获取队列大小
inline int ThreadPool::TasksSize()
{
    std::unique_lock<std::mutex> lock(queue_mutex);
    return tasks.size();
}